package com.itfreer.print.base.itextpdf.textbefore;

import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itfreer.print.base.itextpdf.ChineseFontsProvider;
import com.itfreer.print.base.itextpdf.ITextBefore;

/**
 * 定义pdf的head和foot信息
 * @author chenxu
 *
 */
public class CenterHeadInfoTextBefore implements ITextBefore {
	
	private String msg;
	
	public CenterHeadInfoTextBefore(String msg){
		this.msg = msg;
	}
	
	/**
	 * 文档操作
	 * @param pdfDocument
	 * @param pdfWriter
	 */
	public void doOptions(Document pdfDocument, PdfWriter pdfWriter){
		if (pdfWriter == null) {
			return;
		}
		pdfWriter.setPageEvent(new HeadFootInfoPdfPageEvent());
	}
	
	/**
	 * 为PDF分页时创建添加header和footer信息的事件信息
	 */
	private class HeadFootInfoPdfPageEvent extends PdfPageEventHelper {

		public HeadFootInfoPdfPageEvent() {
		}

		public void onEndPage(PdfWriter writer, Document document) {
			try {
				PdfContentByte headAndFootPdfContent = writer.getDirectContent();
				headAndFootPdfContent.saveState();
				headAndFootPdfContent.beginText();
				
				BaseFont bfChinese = ChineseFontsProvider.getYHBaseFont();
				headAndFootPdfContent.setFontAndSize(bfChinese, 10);
				// 文档页头信息设置
				float x = document.top(-20);
				
				String msgString = "";
				if(msg!=null){
					msgString = msg.replace("{page}", String.valueOf(writer.getPageNumber()));
				}
				
				// 页头信息中间
				headAndFootPdfContent.showTextAligned(PdfContentByte.ALIGN_CENTER, 
						msgString, (document.right() + document.left()) / 2, x, 0);
				
				headAndFootPdfContent.endText();
				headAndFootPdfContent.restoreState();
			} catch (DocumentException de) {
				de.printStackTrace();
				System.err.println("pdf watermark font: " + de.getMessage());
			} catch (IOException de) {
				de.printStackTrace();
				System.err.println("pdf watermark font: " + de.getMessage());
			}
		}
	}
}
